package com.julian.warehouse.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;

import com.julian.warehouse.R;
import com.julian.warehouse.adapter.RukuLvAdapter;
import com.julian.warehouse.base.SPBaseActivity;
import com.julian.warehouse.bean.GoodsBean;
import com.julian.warehouse.database.GoodsTable;
import com.julian.warehouse.database.MyDBOpenHelper;
import com.julian.warehouse.database.RecordsTable;
import com.julian.warehouse.interfaces.OnAddReduceClickListener;
import com.julian.warehouse.utils.DateUtil;
import com.julian.warehouse.utils.MyLog;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ChukuActivity extends SPBaseActivity implements View.OnClickListener {


    private SQLiteDatabase db;
    private List<GoodsBean> list;
    private ListView lv;
    private EditText et_gname;
    private RukuLvAdapter adapter;
    public static ChukuActivity instance;
    private List<Map<String,Integer>> rukuCountList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chuku);
        super.init();
        setHeadTitle(true,"出库");
        instance = this;

        Intent intent = getIntent();

        if (intent!=null&&intent.getSerializableExtra("chuku_item")!=null){
            MyLog.i("AA","getIntent不为空");
            GoodsBean chuku_item = (GoodsBean) intent.getSerializableExtra("chuku_item");
            MyLog.i("AA","getIntent的item="+chuku_item.toString());
            list.clear();
            list.add(chuku_item);
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    public void initView() {


        findViewById(R.id.btn_chuku).setOnClickListener(this);
        lv = (ListView) findViewById(R.id.lv);
        et_gname = (EditText) findViewById(R.id.et_gname);
        et_gname.addTextChangedListener(myWatcher);
    }

    @Override
    public void initData() {
        list = new ArrayList<>();


        rukuCountList = new ArrayList<>();

        adapter = new RukuLvAdapter(this, list);
        lv.setAdapter(adapter);

        MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
        db = myDBOpenHelper.getReadableDatabase();
        queryAll();

        adapter.setOnAddReduceClickListener(new OnAddReduceClickListener() {
            @Override
            public void onAddReduceClick(List<Map<String, Integer>> countList) {


                for (int i = 0; i <countList.size() ; i++) {
                    Map<String,Integer> map = countList.get(i);



                    for (Map.Entry<String,Integer> entry : map.entrySet()){

                        for (int j = 0; j < rukuCountList.size(); j++) {
                            if (rukuCountList.get(j).containsKey(entry.getKey())){
                                rukuCountList.remove(j);
                            }
                        }

                    }

                }

                rukuCountList.addAll(countList);


                Log.i("AA","activity中回调监听中最终得到的countlist内容"+rukuCountList.toString());

            }
        });

    }

    private void queryAll(){
         /* Cursor cursor = db.query(
                 GoodsTable.TBL_NAME,
                 new String[]{
                         GoodsTable.COL_ID,
                         GoodsTable.COL_GNAME,
                         GoodsTable.COL_CTIME,
                         GoodsTable.COL_DESCRIPTION,
                         GoodsTable.COL_PICURL,
                         GoodsTable.COL_PRICE,
                         GoodsTable.COL_COUNT
                             },
                         GoodsTable.COL_GNAME+" =?",
                            new String[]{"哇哈哈"},
                            null,
                             null,
                            null,
                            null
             );*/

        //上面的查询方法比较烦，但不易出错
        String sql = "select * from "+ GoodsTable.TBL_NAME;
        Cursor cursor = db.rawQuery(sql, null);
        list.clear();
        while(cursor.moveToNext()){
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setGname(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_GNAME)));
            goodsBean.setCtime(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_CTIME)));
            goodsBean.setDescription(cursor.getString(cursor.getColumnIndex( GoodsTable.COL_DESCRIPTION)));
            goodsBean.setPicurl(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_PICURL)));
            goodsBean.setCount(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_COUNT)));
            goodsBean.setPrice(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_PRICE)));
            goodsBean.setCost(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_COST)));
            goodsBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_ID)));
            list.add(goodsBean);
        }
        cursor.close();
        //db.close();


        MyLog.i("AA","当前记录"+list.toString());
        adapter.notifyDataSetChanged();
    }



    @Override
    public void initEvent() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_chuku:
                long timeStamp = System.currentTimeMillis();
                String time = DateUtil.getStrTimeFromStack(timeStamp + "", "yyyy-MM-dd HH:mm:ss");

                //GoodsBean goodsBean = new GoodsBean("44",time,"picbase64",7,"description",120,100);

                   /* MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
                    db = myDBOpenHelper.getReadableDatabase();*/
                if (rukuCountList.size()==0){
                    showToast("未添加任何产品！");
                    return;
                }

                Log.i("AA","activity中更新时最终得到的countlist内容"+rukuCountList.toString());

                for (int i = 0; i <rukuCountList.size() ; i++) {
                    Map<String,Integer> map = rukuCountList.get(i);
                    for (Map.Entry<String,Integer> entry : map.entrySet()){
                        Log.i("AA","键值对--key="+entry.getKey()+",value="+entry.getValue()+"rukuCountList.size()="+rukuCountList.size());
                        //逐条执行入库操作
                        updateCountByName(entry.getKey(),entry.getValue());
                    }


                }

                showToast("出库完成！");

                finish();




                /*
                    ContentValues values = new ContentValues();
                    values.put(GoodsTable.COL_GNAME,goodsBean.getGname());
                    values.put(GoodsTable.COL_CTIME,goodsBean.getCtime());
                    values.put(GoodsTable.COL_PICURL,goodsBean.getPicurl());
                    values.put(GoodsTable.COL_COUNT,goodsBean.getCount());
                    values.put(GoodsTable.COL_DESCRIPTION,goodsBean.getDescription());
                    values.put(GoodsTable.COL_PRICE, goodsBean.getPrice());
                    values.put(GoodsTable.COL_COST, goodsBean.getCost());
                    long id = db.insert(
                            GoodsTable.TBL_NAME,
                            null,
                            values
                    );
                    //db.close();

                    MyLog.i("AA","入库结果="+id);


                    if(id!=-1){
                        showToast("入库成功！");
                    }else {
                        showToast("入库失败，请重试！");
                    }*/

                break;

            default:break;
        }
    }

    private TextWatcher myWatcher =  new TextWatcher(){

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            findGoodsByName(s.toString().trim());
            MyLog.i("AA","触发afterTextChanged");

        }
    };

    private void findGoodsByName(String gname) {
        if (gname.equals("")){
            queryAll();
            return;
        }

       /* MyDBOpenHelper myDBOpenHelper = new MyDBOpenHelper(this);
        db = myDBOpenHelper.getReadableDatabase();*/
        //上面的查询方法比较烦，但不易出错
        String sql = "select * from "+GoodsTable.TBL_NAME+" where GNAME LIKE '%"+gname+"%'";
        Cursor cursor = db.rawQuery(sql, null);
        list.clear();
        while(cursor.moveToNext()){
            GoodsBean goodsBean = new GoodsBean();
            goodsBean.setGname(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_GNAME)));
            goodsBean.setCtime(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_CTIME)));
            goodsBean.setDescription(cursor.getString(cursor.getColumnIndex( GoodsTable.COL_DESCRIPTION)));
            goodsBean.setPicurl(cursor.getString(cursor.getColumnIndex(GoodsTable.COL_PICURL)));
            goodsBean.setCount(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_COUNT)));
            goodsBean.setPrice(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_PRICE)));
            goodsBean.setCost(cursor.getDouble(cursor.getColumnIndex(GoodsTable.COL_COST)));
            goodsBean.setId(cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_ID)));

            list.add(goodsBean);
        }
        cursor.close();
        //db.close();
        adapter.notifyDataSetChanged();



    }



    private void updateCountByName(String gname,int count){
        Log.i("AA","即将插入--gname="+gname+"&count="+count);

        String sql_queryCount = "select "+GoodsTable.COL_COUNT+" from "+GoodsTable.TBL_NAME+" where "+GoodsTable.COL_GNAME+" = '"+gname+"'";
        Cursor cursor = db.rawQuery(sql_queryCount, null);
        cursor.moveToNext();
        int oragCount = cursor.getInt(cursor.getColumnIndex(GoodsTable.COL_COUNT));
        if (count>oragCount){
            showToast("产品"+gname+"出库数量不足！");
            return;
        }


        String sql = "UPDATE "+GoodsTable.TBL_NAME +
                " SET "+GoodsTable.COL_COUNT+" = "+GoodsTable.COL_COUNT+" - "+count+" WHERE "+GoodsTable.COL_GNAME+" = '"+gname+"'";
        String result = "成功";
        try {
            db.execSQL(sql);
        }catch (SQLException e){
            showToast(gname+"出库失败！");
            result="失败";
        }

        //将记录添加进records表
        long timeStamp = System.currentTimeMillis();
        String time = DateUtil.getStrTimeFromStack(timeStamp + "", "yyyy-MM-dd HH:mm:ss");

        ContentValues values = new ContentValues();
        values.put(RecordsTable.COL_GNAME,gname);
        values.put(RecordsTable.COL_CTIME,time);
        values.put(RecordsTable.COL_COUNT,count);
        values.put(RecordsTable.COL_FLAG,1);//0代表入库操作，1出库
        values.put(RecordsTable.COL_RESULT,result);//入库成功or失败
        long id = db.insert(
                RecordsTable.TBL_NAME,
                null,
                values
        );

        Log.i("AA","入库操作添加进记录表结果---id="+id);


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        db.close();
    }
}
